<template>
  <div>
    <el-dialog :title="title" width="800px" :visible.sync="pageShowFlag" v-model="pageShowFlag" :show-close="false" append-to-body :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="form" class="add-bg" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input class="mw300" v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input class="mw300" v-model="formData.description"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="formData.categoryId" class="w300" placeholder="请选择所属分类">
            <el-option v-for="item in cateList" :key="item.id" :label="item.categoryName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\..*)\./g, '$1').replace(/^\./, '0.').replace(/(\.\d{2})\d+/, '$1');"
              class="mw300" v-model="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="豆子" prop="bean">
          <el-select class="w300" v-model="formData.bean" placeholder="请选择" multiple>
            <el-option
                v-for="item in beansList"
                :key="item.beanValue"
                :label="item.beanName"
                :value="item.beanValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specList">
          <div v-for="(spec, index) in formData.specList" :key="index" class="mb-10">
            <el-input
                v-model="spec.specName"
                placeholder="规格名称"
                class="w200 mr-10"
                @blur="handleSpecChange(spec, index, 'specName')"
            ></el-input>
            <el-input
                v-model="spec.specPrice"
                placeholder="加价金额"
                class="w150 mr-10"
                @blur="handleSpecChange(spec, index, 'specPrice')"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\..*)\./g, '$1').replace(/^\./, '0.').replace(/(\.\d{2})\d+/, '$1');"
            ></el-input>
            <el-input
                v-model="spec.weight"
                placeholder="克重"
                class="w150 mr-10"
                @blur="handleSpecChange(spec, index, 'specPrice')"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\..*)\./g, '$1').replace(/^\./, '0.').replace(/(\.\d{2})\d+/, '$1');"
            ></el-input>
            <el-button type="danger" icon="el-icon-delete" circle @click="removeSpec(index)"></el-button>
          </div>
          <el-button type="primary" @click="addSpec">添加规格</el-button>
        </el-form-item>

        <!-- 做法管理部分 - 带分区的做法 -->
        <el-form-item label="做法" prop="cooksList">
          <div v-for="(group, groupIndex) in formData.cooksList" :key="'group-'+groupIndex" class="cook-group mb-20">
            <div class="group-header flex-between mb-10">
              <el-input
                  v-model="group.cooksTitle"
                  placeholder="做法分区标题(如:温度)"
                  class="w200 mr-10"
                  @blur="handleCookGroupChange(group, groupIndex, 'cooksTitle')"
              ></el-input>
              <el-button type="danger" icon="el-icon-delete" circle @click="removeCookGroup(groupIndex)"></el-button>
            </div>

            <div v-for="(cook, cookIndex) in group.cookItems" :key="'cook-'+cookIndex" class="cook-item mb-10 ml-20">
              <el-input
                  v-model="cook.cookName"
                  placeholder="做法名称"
                  class="w200 mr-10"
                  @blur="handleCookChange(cook, groupIndex, cookIndex, 'cookName')"
              ></el-input>
              <el-input
                  v-model="cook.cookPrice"
                  placeholder="加价金额"
                  class="w150 mr-10"
                  @blur="handleCookChange(cook, groupIndex, cookIndex, 'cookPrice')"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/(\..*)\./g, '$1').replace(/^\./, '0.').replace(/(\.\d{2})\d+/, '$1');"
              ></el-input>
              <el-button type="danger" icon="el-icon-delete" circle @click="removeCook(groupIndex, cookIndex)"></el-button>
            </div>
            <el-button type="primary" class="ml-20" @click="addCook(groupIndex)">添加做法</el-button>
          </div>
          <el-button type="primary" @click="addCookGroup">添加做法分区</el-button>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="mainImgs">
          <ImageUploader v-model="formData.mainImgs" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input class="mw300" type="textarea" v-model="formData.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClick">提交</el-button>
        <el-button @click="$emit('closeDialog')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  KAFEE_GET_BEANS_LIST,
  KAFEE_GET_DISH_DETAIL,
  KAFEE_GET_GOODS_LIST,
  KAFEE_POST_ADD_DISH,
  KAFEE_POST_CATE_LIST,
  KAFEE_POST_DELETE_SPEC,
  KAFEE_POST_EDIT_DISH,
  KAFEE_POST_SPEC_ADD,
  KAFEE_POST_UPDATE_SPEC,
  KAFEE_POST_UPLOADS,
  KAFEE_POST_COOK_ADD,
  KAFEE_POST_COOK_UPDATE,
  KAFEE_POST_COOK_DELETE,
  KAFEE_POST_COOK_GROUP_ADD,
  KAFEE_POST_COOK_GROUP_UPDATE,
  KAFEE_POST_COOK_GROUP_DELETE,
  ORDERING_GET_GEARS_LIST,
  ORDERING_ORDERING_POST, KAFEE_POST_SPEC_UPDATE
} from "@/assets/const/api";
import {getStore} from "js-utils";
import {getRandomKey} from "@/config/util";
import {mapState} from "vuex";
import {Validate} from "js-utils/validate";
import ImageUploader from "@/components/ImageUploader.vue";
import {dlParseJSON} from "@/config/tools";
export default {
  name: '',
  mixins: [],
  components: {ImageUploader},
  props: {
    showFlag:Boolean,
    title:String,
    editRow:Object
  },
  data() {
    return {
      tableData: [],
      gearList: [],
      cateList:[],
      pageShowFlag:false,
      beansList:[],
      formData: {
        name: '',
        categoryId:'',
        mainImgs:'',
        categoryName: '',
        remark: '',
        flagTakeOff: 1,
        price: '',
        bean:'',
        state:0,
        specList: [],
        cooksList: [] // 修改为带分区的做法数据结构
      },
      rules: {
        name: [{required: true, message: '商品名称不能为空', trigger: 'blur'}],
        price: [{required: true, message: '金额不能为空', trigger: 'blur'}],
        bean: [{required: true, message: '请选择豆子', trigger: 'blur'}],
        targetDate: [{required: true, message: '生效时间不能为空', trigger: 'blur'}],
      },
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo || {};
    }
  },
  watch: {},
  created() {
  },
  mounted() {
    this.pageShowFlag = this.showFlag;
    if (!Validate.isEmpty(this.editRow)){
      this.formData = {...this.editRow, specList: [], cooksList: []}
    }
    this.getCateList();
    this.getBeans();
    if (!Validate.isEmpty(this.editRow)){
      this.getDishDetail();
    }
  },
  methods: {
    getDishDetail(){
      this.$http.get(KAFEE_GET_DISH_DETAIL,{id:this.editRow.id}).then(res => {
        let {specList=[], cooksList=[]} = res.data ||{};
        if (!Validate.isEmpty(specList)){
          this.$nextTick(()=>{
            this.formData.specList = specList;
          });
        }
        if (!Validate.isEmpty(cooksList)){
          let groups = [...cooksList].map(v=>({...v,cookItems:[]}));
          groups.forEach(e=>{
            let arr = dlParseJSON(e.cooksData);
            e.cookItems = arr;
          })
          this.$nextTick(()=>{
            this.formData.cooksList = groups.filter(v=>!Validate.isEmpty(v.cookItems));
          });
        }
      });
    },
    getBeans(){
      this.$http.get(KAFEE_GET_BEANS_LIST).then(res => {
        this.beansList = res.data ||[];
      });
    },
    getCateList(){
      let param = {current:1, size:9999,}
      this.$http.get(KAFEE_POST_CATE_LIST,param).then(res => {
        this.cateList = res.data?.records||[];
        if (!Validate.isEmpty(this.cateList) && Validate.isEmpty(this.formData.categoryId)){
          let first = this.cateList[0];
          this.formData.categoryId = first.id;
        }
      });
    },
    choseImage() {
      this.$refs.fileInput.click();
    },
    handleFileChange(e) {
      if (!Validate.isEmpty(e.target.files)){
        let file = e.target.files[0];
        const formData = new FormData();
        formData.append('file', file);
        this.$http.upload({file:file}).then(res=>{
          this.formData.mainImgs = res.data;
        });
      }
    },
    deleteClick(row) {
      this.tableData = this.tableData.filter(v => v.key !== row.key)
    },
    submitClick() {
      this.$refs['form'].validate((valid, object) => {
        if (valid) {
          this.handleSave();
        } else {
          let key = Object.keys(object)[0];
          this.$message.error(object[key][0].message);
          return false;
        }
      });
    },
    async handleSave() {
      if (!Validate.isEmpty(this.cateList)){
        let obj = this.cateList.find(v=>v.id === this.formData.categoryId);
        if (obj){
          this.formData.categoryName = obj.categoryName;
        }
      }
      let url = KAFEE_POST_ADD_DISH;
      let dic = {...this.formData};
      if (!Validate.isEmpty(this.editRow)){
        url = KAFEE_POST_EDIT_DISH;
        dic['id'] = this.editRow.id;
      }

      try {
        const res = await this.$http.post(url, dic);
        if (res.code === 200) {
          let tid = !Validate.isEmpty(this.editRow) ? dic.id : res.data;

          // 处理规格
          if (tid && !Validate.isEmpty(this.formData.specList)) {
            for (const e of this.formData.specList) {
              let specUrl = Validate.isEmpty(e.id)?KAFEE_POST_SPEC_ADD:KAFEE_POST_SPEC_UPDATE;
              let eDic = {specName:e.specName, specPrice:e.specPrice, goodsId:tid,tid:getRandomKey()};
              if (!Validate.isEmpty(e.id)){
                eDic['id'] = e.id;
              }
              await this.$http.post(specUrl, eDic);
            }
          }

          // 处理做法分组和做法
          if (tid && !Validate.isEmpty(this.formData.cooksList)) {
            for (const group of this.formData.cooksList) {
              // 保存做法分组
              group.cookItems = group.cookItems.map(v=>({...v,tid:getRandomKey()}));
              let json = JSON.stringify(group.cookItems);
              let groupDic = {cooksTitle: group.cooksTitle, goodsId: tid,cooksData:json,tid:getRandomKey()};
              let cookUrl = Validate.isEmpty(group.id)?KAFEE_POST_COOK_ADD:KAFEE_POST_COOK_UPDATE;
              if (!Validate.isEmpty(group.id)){
                groupDic['id'] = group.id;
              }
              await this.$http.post(cookUrl, groupDic);
            }
          }
          this.$message.success('提交成功');
          this.$emit('closeDialog');
        }
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('提交失败');
      }
    },
    getOrderTimetext(row) {
      let gear = this.gearList.find(v => v.value === row.timeRange)
      if (gear) {
        return gear.ableStartTime + '-' + gear.ableEndTime
      }
      return '-'
    },
    addDishClick() {
      this.$refs['form'].validate((valid, object) => {
        if (valid) {
          let dic = {...this.formData}
          dic.flagSend = dic.flagSend ? 1 : 0
          dic['key'] = getRandomKey()
          this.tableData.push(dic)
        } else {
          let key = Object.keys(object)[0];
          this.$message.error(object[key][0].message);
          return false;
        }
      });
    },
    // 规格相关方法
    addSpec() {
      this.formData.specList.push({ specName: '', specPrice: '' });
    },
    removeSpec(index) {
      let spec = this.formData.specList[index];
      if (!Validate.isEmpty(this.editRow) && !Validate.isEmpty(spec) && spec.id){
        this.$http.post(KAFEE_POST_DELETE_SPEC,{id:spec.id}).then(res => {
          this.$message.success('删除成功');
          this.formData.specList.splice(index, 1);
        });
      }else{
        this.formData.specList.splice(index, 1);
      }
    },
    handleSpecChange(spec, index, field) {
      if (!Validate.isEmpty(this.editRow) && spec.id) {
        const updateData = {
          id: spec.id,
          specName: spec.specName,
          specPrice: spec.specPrice,
          goodsId: this.editRow.id,
        };

        this.$http.post(KAFEE_POST_UPDATE_SPEC, updateData)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('规格更新成功');
              } else {
                this.$message.error('规格更新失败');
              }
            })
            .catch(error => {
              console.error('更新规格出错:', error);
              this.$message.error('规格更新失败');
            });
      }
    },

    // 做法相关方法 - 带分区的做法
    addCookGroup() {
      this.formData.cooksList.push({
        cooksTitle: '',
        cookItems: []
      });
    },
    removeCookGroup(groupIndex) {
      let group = this.formData.cooksList[groupIndex];
      if (!Validate.isEmpty(this.editRow) && !Validate.isEmpty(group) && group.id){
        let groupDic = {cooksTitle: group.cooksTitle,id:group.id, goodsId: this.editRow.id,cooksData:'[]',tid:getRandomKey()};
        this.$http.post(KAFEE_POST_COOK_UPDATE, groupDic).then(res=>{
          this.$message.success('删除分区成功');
          this.formData.cooksList.splice(groupIndex, 1);
        });
      }else{
        this.formData.cooksList.splice(groupIndex, 1);
      }
    },
    handleCookGroupChange(group, groupIndex, field) {
      if (!Validate.isEmpty(this.editRow) && group.id) {
        const updateData = {
          id: group.id,
          cooksTitle: group.cooksTitle,
          goodsId: this.editRow.id,
        };

        this.$http.post(KAFEE_POST_COOK_GROUP_UPDATE, updateData)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('分区更新成功');
              } else {
                this.$message.error('分区更新失败');
              }
            })
            .catch(error => {
              console.error('更新分区出错:', error);
              this.$message.error('分区更新失败');
            });
      }
    },
    addCook(groupIndex) {
      this.formData.cooksList[groupIndex].cookItems.push({
        cookName: '',
        cookPrice: ''
      });
    },
    async removeCook(groupIndex, cookIndex) {
      this.formData.cooksList[groupIndex].cookItems.splice(cookIndex, 1);
      if (!Validate.isEmpty(this.editRow) && !Validate.isEmpty(this.formData.cooksList)) {
        for (const group of this.formData.cooksList) {
          // 保存做法分组
          let json = JSON.stringify(group.cookItems);
          let groupDic = {cooksTitle: group.cooksTitle,id:group.id, goodsId: this.editRow.id, cooksData: json};
          await this.$http.post(KAFEE_POST_COOK_UPDATE, groupDic);
        }
      }
    },
    handleCookChange(cook, groupIndex, cookIndex, field) {
      if (!Validate.isEmpty(this.editRow) && cook.id) {
        const updateData = {
          id: cook.id,
          cookName: cook.cookName,
          cookPrice: cook.cookPrice,
          goodsId: this.editRow.id,
          cookGroupId: this.formData.cooksList[groupIndex].id
        };

        this.$http.post(KAFEE_POST_COOK_UPDATE, updateData)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('做法更新成功');
              } else {
                this.$message.error('做法更新失败');
              }
            })
            .catch(error => {
              console.error('更新做法出错:', error);
              this.$message.error('做法更新失败');
            });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.add-bg{
  max-height: 500px;
  overflow-y: auto;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  border: 1px dashed #a2a2a2;
  border-radius: 10px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.cook-group {
  border: 1px solid #eaeaea;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 15px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cook-item {
  display: flex;
  align-items: center;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-20 {
  margin-bottom: 20px;
}

.ml-20 {
  margin-left: 20px;
}
</style>